import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by 郭浩 on 2020/9/23 17:02
 */
public class DBUtilsTest {
    @Test
    public void testQueryRunner() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        Employee e = queryRunner.query("select * from t_employee", new ResultSetHandler<Employee>() {

            @Override
            public Employee handle(ResultSet resultSet) throws SQLException {
                resultSet.next();
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                double salary = resultSet.getDouble("salary");
                Employee employee = new Employee(id, name, salary);
                return employee;
            }
        });
        System.out.println(e);
    }

    @Test
    public void BeanHandler() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        Employee e = queryRunner.query("select * from t_employee", new BeanHandler<>(Employee.class));
        System.out.println(e);
    }

    @Test
    public void BeanHandlerList() throws SQLException {
        DataSource dataSource = DruidUtils.getDataSource();
        QueryRunner queryRunner = new QueryRunner(dataSource);
        List<Employee> employeeList = null;
        try {
            employeeList = queryRunner.query("select * from t_employee", new BeanListHandler<>(Employee.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        for (int i = 0; i < employeeList.size(); i++) {
            Employee employee = employeeList.get(i);
            System.out.println(employee);
        }
    }
}
